<template>
  <div class="raceGroup">
    <div class="r-header">
      <div class="r-h-title"> <i class="iconfont icon-tuanduishezhi"></i>比赛团队管理</div>
    </div>
    <div class="r-search">
      <!-- <n-input class="r-s-input" placeholder="搜索比赛" round size="small" v-model:value="searchVal">
        <template #suffix>
          <i class="iconfont icon-sousuo" @click="searchParams.name"></i>
        </template>
</n-input> -->
      <n-button class="r-s-btn" size="small" round type="success" @click="isShowCreateTeam = true"><i
          class="iconfont icon-tianjia"></i>创建</n-button>
    </div>
    <div class="r-table">
      <el-table class="table" :data="groups.records" size="small" stripe>
        <el-table-column type="index" label="序号" width="100%" align="center" :index="indexMethod" />
        <el-table-column prop="cid" label="比赛ID" align="center"></el-table-column>
        <el-table-column prop="name" label="团队名称" align="center"></el-table-column>
        <el-table-column label="人数/上限" align="center">
          <template #default="scoped">
            {{ scoped.row.groupUsers.length + '/' + route.params.limit }}
          </template>
        </el-table-column>
        <el-table-column prop="leader" label="队长" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div class="btns">
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button class="btn" size="tiny" type="success"
                    @click="isShowEditTeam = true, currentTeam = scoped.row">
                    <i class="iconfont icon-bianji"></i>
                  </n-button>
                </template>
                编辑团队
              </n-tooltip>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button class="btn" size="tiny" type="info" @click="updateCurrent(scoped.row)">
                    <i class="iconfont icon-yonghu"></i>
                  </n-button>
                </template>
                查看成员
              </n-tooltip>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button class="btn" size="tiny" type="error" @click="delGroup(scoped.row.id)">
                    <i class="iconfont icon-shanchu"></i>
                  </n-button>
                </template>
                删除
              </n-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="r-footer">
      <el-pagination class="pagination" :page-sizes="[50, 100]" background small layout="prev, pager, next,sizes"
        :total="Number(groups.total)" v-model:current-page="searchParams.pageNum"
        v-model:page-size="searchParams.pageSize" />
    </div>
    <!-- 团队成员列表 -->
    <el-drawer v-model="isShowUsers" :show-close="false" direction="rtl" class="drawer" :size="isShowUsersSize"
      @close="isShowUsersSize = '50%'">
      <template #header="{ close, titleId, titleClass }">
        <h1 :id="titleId" :class="titleClass">团队成员列表&emsp;
          <n-button size="tiny" type="success" round @click="isShowUsersSize = '100%', isShowUsers_create = true">
            <i class="iconfont icon-tianjia"></i>添加成员
          </n-button>
        </h1>
        <n-button size="small" round strong secondary type="error" @click="close">
          <i class="iconfont icon-chahao1"></i>
        </n-button>
      </template>
      <el-table class="table" :data="current.groupUsers">
        <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="number" label="学号" align="center">
          <template #default="scoped">{{ scoped.row.number || "--" }}</template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" align="center">
          <template #default="scoped">{{ scoped.row.realName || "--" }}</template>
        </el-table-column>
        <el-table-column label="院校" align="center">
          <template #default="scoped">
            <div class="desc">{{
              (scoped.row.school || "") +
              "-" +
              (scoped.row.college || "") +
              "-" +
              (scoped.row.major || "")
            }}</div>
          </template>
        </el-table-column>
        <el-table-column label="职位" align="center">
          <template #default="scoped">
            <n-tag size="small" type="success" v-if="current.leader == scoped.row.username">队长</n-tag>
            <n-tag size="small" type="success" v-else>队员</n-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div class="btns">
              <el-tooltip content="移出队伍" placement="top">
                <n-button class="btn" size="tiny" type="error" @click="removeFromTeam(current.id, scoped.row.uid)">
                  <i class="iconfont icon-shanchu"></i>
                </n-button>
              </el-tooltip>
              <el-tooltip content="设为队长" placement="top">
                <n-button class="btn" size="tiny" type="warning" :disabled="current.leader == scoped.row.username"
                  @click="updateRaceTeam(current.id, scoped.row.uid, current.name)">
                  <i class="iconfont icon-zuozhe"></i>
                </n-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <el-drawer v-model="isShowUsers_create" :show-close="false" direction="rtl" class="drawer" size="50%"
      @close="isShowUsersSize = '50%'">
      <template #header="{ close, titleId, titleClass }">
        <div :id="titleId" :class="titleClass">
          <h3>可选用户列表</h3>
          <div class="h1box">
            <n-input class="r-s-input" placeholder="搜索用户" round size="small" v-model:value="searchVal_name">
              <template #suffix>
                <i class="iconfont icon-sousuo" @click="userParams.name = searchVal_name"></i>
              </template>
            </n-input>
            <el-select class="popselect" v-model="userParams.isReg" size="small">
              <el-option label="已报名" :value="1" />
              <el-option label="未报名" :value="0" />
            </el-select>
            <n-input class="r-s-input" placeholder="搜索班级" round size="small" v-model:value="searchVal_major">
              <template #suffix>
                <i class="iconfont icon-sousuo" @click="userParams.major = searchVal_major"></i>
              </template>
            </n-input>
            <el-select class="popselect" v-model="userParams.majorLike" size="small">
              <el-option label="模糊查询" :value="0" />
              <el-option label="精准查询" :value="1" />
            </el-select>
            <transition>
              <n-button v-show="newSelection.length > 0" class="btn" size="tiny" round type="success"
                style="margin:auto 10px auto auto" @click="appendMore">批量添加</n-button>
            </transition>
          </div>

        </div>
        <n-button size="tiny" round strong secondary type="error" @click="close">
          <i class="iconfont icon-chahao1"></i>
        </n-button>
      </template>
      <el-table class="table" :data="raceUsers.records" @selection-change="changeSelectedUser">
        <el-table-column type="selection" align="center" />
        <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="number" label="学号" align="center">
          <template #default="scoped">{{ scoped.row.number || "--" }}</template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" align="center">
          <template #default="scoped">{{ scoped.row.realName || "--" }}</template>
        </el-table-column>
        <el-table-column label="院校" align="center">
          <template #default="scoped">
            <div class="desc">{{
              (scoped.row.school || "") +
              "-" +
              (scoped.row.college || "") +
              "-" +
              (scoped.row.major || "")
            }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div class="btns">
              <el-tooltip content="设为新队伍队长" placement="top" v-if="isShowCreateTeam == true">
                <n-button class="btn" size="tiny" type="warning"
                  @click="teamMsg.uid = scoped.row.id, teamMsg.username = scoped.row.username, isShowUsers_create = false">
                  <i class="iconfont icon-zuozhe"></i>
                </n-button>
              </el-tooltip>
              <el-tooltip content="加入队伍" placement="top" v-else>
                <n-button class="btn" size="tiny" type="success" @click="appendUserIntoTeam(scoped.row.id)">
                  <i class="iconfont icon-tijiao1"></i>
                </n-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <el-pagination class="pagination" :page-sizes="[50, 99]" background small layout="prev, pager, next,sizes"
          :total="Number(raceUsers.total)" v-model:current-page="userParams.pageNum"
          v-model:page-size="userParams.pageSize" />
      </div>
    </el-drawer>

    <el-dialog v-model="isShowCreateTeam" title="创建团队" width="500">
      <div class="teaminput">
        <div class="box">
          队伍名称：
          <n-input size="small" class="input" placeholder="" v-model:value="teamMsg.name"></n-input>
        </div>
        <div class="box">
          选择队长：
          <n-button v-show="teamMsg.username.length == 0" class="btn" type="success" round size="small"
            @click="isShowUsers_create2 = true">
            <i class="iconfont icon-zuozhe"></i>
          </n-button>
          <n-tag v-show="teamMsg.username.length > 0" class="btn" type="success" round size="small" closable
            @close="handleClose()">
            <i class="iconfont icon-zuozhe"></i>{{ teamMsg.username }}
          </n-tag>
        </div>
      </div>
      <el-drawer v-model="isShowUsers_create2" :show-close="false" direction="rtl" class="drawer" size="50%">
        <template #header="{ close, titleId, titleClass }">
          <div :id="titleId" :class="titleClass">
            <h3>可选用户列表</h3>
            <div class="h1box">
              <n-input class="r-s-input" placeholder="搜索用户" round size="small" v-model:value="searchVal_name">
                <template #suffix>
                  <i class="iconfont icon-sousuo" @click="userParams.name = searchVal_name"></i>
                </template>
              </n-input>
              <el-select class="popselect" v-model="userParams.isReg" size="small">
                <el-option label="已报名" :value="1" />
                <el-option label="未报名" :value="0" />
              </el-select>
            </div>
          </div>
          <n-button size="small" round strong secondary type="error" @click="close">
            <i class="iconfont icon-chahao1"></i>
          </n-button>
        </template>
        <el-table class="table" :data="raceUsers.records">
          <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod"></el-table-column>
          <el-table-column prop="username" label="用户名" align="center"></el-table-column>
          <el-table-column prop="number" label="学号" align="center">
            <template #default="scoped">{{ scoped.row.number || "--" }}</template>
          </el-table-column>
          <el-table-column prop="realName" label="真实姓名" align="center">
            <template #default="scoped">{{ scoped.row.realName || "--" }}</template>
          </el-table-column>
          <el-table-column label="院校" align="center">
            <template #default="scoped">
              <div class="desc">{{
                (scoped.row.school || "") +
                "-" +
                (scoped.row.college || "") +
                "-" +
                (scoped.row.major || "")
              }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scoped">
              <div class="btns">
                <el-tooltip content="设为新队伍队长" placement="top" v-if="isShowCreateTeam == true">
                  <n-button class="btn" size="tiny" type="warning"
                    @click="teamMsg.uid = scoped.row.id, teamMsg.username = scoped.row.username, isShowUsers_create2 = false">
                    <i class="iconfont icon-zuozhe"></i>
                  </n-button>
                </el-tooltip>
                <el-tooltip content="加入队伍" placement="top" v-else>
                  <n-button class="btn" size="tiny" type="success" @click="appendUserIntoTeam(scoped.row.id)">
                    <i class="iconfont icon-tijiao1"></i>
                  </n-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="footer">
          <el-pagination class="pagination" :page-sizes="[50, 99]" background small layout="prev, pager, next,sizes"
            :total="Number(raceUsers.total)" v-model:current-page="userParams.pageNum"
            v-model:page-size="userParams.pageSize" />
        </div>
      </el-drawer>
      <template #footer>
        <div class="dialog-footer">
          <n-button class="btn" round @click="isShowCreateTeam = false">取消</n-button>
          <n-button class="btn" round type="success" @click="isShowCreateTeam = false, appendRaceTeam()">
            确定
          </n-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="isShowEditTeam" title="编辑团队" width="500">
      <div class="teaminput">
        <div class="box">
          队伍名称：<n-input size="small" class="input" placeholder="" v-model:value="currentTeam.name"></n-input>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <n-button class="btn" round @click="isShowEditTeam = false">取消</n-button>
          <n-button class="btn" round type="success"
            @click="isShowEditTeam = false, updateRaceTeam(currentTeam.id, currentTeam.uid, currentTeam.name)">
            确定
          </n-button>
        </div>
      </template>
    </el-dialog>


    <!-- 可选用户列表 -->
    <!-- <el-drawer v-model="isShowUsers_create" :show-close="false" direction="rtl" class="drawer" size="50%">
      <template #header="{ close, titleId, titleClass }">
        <h1 :id="titleId" :class="titleClass">可选用户列表
          <el-select class="popselect" v-model="userParams.isReg" size="small">
            <el-option label="不含报名用户" :value="1" />
            <el-option label="含报名用户" :value="0" />
          </el-select>
        </h1>
        <n-button size="small" round strong secondary type="error" @click="close">
          <i class="iconfont icon-chahao1"></i>
        </n-button>
      </template>
      <el-table class="table" :data="raceUsers.records">
        <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="number" label="学号" align="center">
          <template #default="scoped">{{ scoped.row.number || "--" }}</template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" align="center">
          <template #default="scoped">{{ scoped.row.realName || "--" }}</template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" align="center">
          <template #default="scoped">{{ scoped.row.nickname || "--" }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div class="btns">
              <el-tooltip content="设为新队伍队长" placement="top" v-if="isShowCreateTeam == true">
                <n-button class="btn" size="tiny" type="warning"
                  @click="teamMsg.uid = scoped.row.id, teamMsg.username = scoped.row.username, isShowUsers_create = false">
                  <i class="iconfont icon-zuozhe"></i>
                </n-button>
              </el-tooltip>
              <el-tooltip content="加入队伍" placement="top" v-else>
                <n-button class="btn" size="tiny" type="success" @click="appendUserIntoTeam(scoped.row.id)">
                  <i class="iconfont icon-tijiao1"></i>
                </n-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <el-pagination class="pagination" :page-sizes="[20, 50, 99]" background small layout="prev, pager, next,sizes"
          :total="Number(raceUsers.total)" v-model:current-page="userParams.pageNum"
          v-model:page-size="userParams.pageSize" />
      </div>
    </el-drawer> -->
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { getGroupListAPI, delGroupAPI, removeFromTeamAPI, getRaceUsersNoIncludeLeaderAPI, updateRaceTeamAPI, appendRaceTeamAPI, appendUserIntoTeamAPI } from "@/api/adminAPI/adminAPI"
import { debounce } from "@/utils/global.js"
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
const route = useRoute()
const searchVal_name = ref('')
const searchVal_major = ref('')
const searchParams = reactive({
  pageNum: 1,
  pageSize: 50,
  cid: ''
})
watch(searchParams, () => {
  getGroupList()
})
const groups = ref({
  records: [],
  total: 20
})
const getGroupList = debounce(async () => {
  await getGroupListAPI(searchParams).then(res => {
    if (res.data.code === 200) {
      groups.value = res.data.data
      if (isShowUsers.value) {
        groups.value.records.forEach(ele => {
          if (ele.id == current.value.id) {
            current.value = ele
          }
        })
      }
    }
  }).catch(err => {
    console.log(err)
  })
}, 100)
onMounted(() => {
  searchParams.cid = route.params.cid
  userParams.cid = route.params.cid
})

const indexMethod = (index) => {
  return (searchParams.pageNum - 1) * searchParams.pageSize + index + 1
}

const isShowUsers = ref(false)
const current = ref({
  id: '',
  groupUsers: []
})
const updateCurrent = (row) => {
  current.value = row
  isShowUsers.value = true
}

//删除队伍
const delGroup = debounce(async (id) => {
  await delGroupAPI([id]).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      getGroupList()
    }
  }).catch(err => {
    console.log(err)
  })
}, 100)

//移除队员
const removeFromTeam = debounce(async (cgid, uid) => {
  await removeFromTeamAPI(cgid, [uid]).then(res => {
    if (res.data.code === 200) {
      isShowUsers.value = false
      ElMessage.success(res.data.msg)
      getGroupList()
    }
  }).catch(err => {
    console.log(err)
  })
}, 100)

//创建团队
const isShowCreateTeam = ref(false)
const teamMsg = ref({
  name: '',
  cid: '',
  uid: '',
  username: ''
})
onMounted(() => {
  teamMsg.value.cid = route.params.cid
})
const isShowUsers_create = ref(false)
const isShowUsers_create2 = ref(false)

const appendRaceTeam = debounce(async () => {
  delete teamMsg.value.username
  await appendRaceTeamAPI([teamMsg.value]).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      getGroupList()
      teamMsg.value = {
        name: '',
        cid: route.params.cid,
        uid: '',
        username: ''
      }
    }
  }).catch(err => {
    console.log(err)
  })
}, 100)
const handleClose = () => {
  teamMsg.value.username = ''
  teamMsg.value.uid = ''
}
//获取注册/未注册的用户
const userParams = reactive({
  pageNum: 1,
  pageSize: 50,
  name: '',
  cid: '',
  isReg: 1,
  isLeader: 1,
  major: '',
  majorLike: 0
})
watch(userParams, () => {
  getRaceUsersNoIncludeLeader()
})
const raceUsers = ref({
  records: [],
  total: 20
})
const getRaceUsersNoIncludeLeader = debounce(async () => {
  await getRaceUsersNoIncludeLeaderAPI(userParams).then(res => {
    if (res.data.code === 200) {
      raceUsers.value = res.data.data
    }
  }).catch(err => {
    console.log(err)
  })
}, 100)

//更新团队队长
const updateRaceTeam = debounce(async (id, uid, name) => {
  const a = {
    id: id,
    uid: uid,
    name: name
  }
  await updateRaceTeamAPI(a).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      getGroupList()
    }
  }).catch(err => {
    console.log(err)
  })
}, 100)

//更新团队名称
const isShowEditTeam = ref(false)
const currentTeam = ref({})


const isShowUsersSize = ref('50%')
const appendUserIntoTeam = debounce(async (uid) => {
  await appendUserIntoTeamAPI(route.params.cid, current.value.id, [uid]).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      getGroupList()
      getRaceUsersNoIncludeLeader()
    }
  }).catch(err => {
    console.log(err)
  })
}, 50)

const newSelection = ref([])
const changeSelectedUser = (newV) => {
  newSelection.value.length = 0
  newV.forEach(ele => {
    newSelection.value.push(ele.id)
  })
}
const appendMore = debounce(async () => {
  await appendUserIntoTeamAPI(route.params.cid, current.value.id, newSelection.value).then(res => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      newSelection.value.length = 0
      getGroupList()
      getRaceUsersNoIncludeLeader()
    }
  }).catch(err => {
    console.log(err)
  })
}, 50)
</script>

<style lang="less" scoped>
.desc {
  font-size: 10px;
}

.raceGroup {
  margin: auto;
  width: 96%;
  height: 92vh;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 12px 12px 50px #d9d9d9,
    -12px -12px 50px #ffffff;
  display: flex;
  flex-direction: column;

  .r-header {
    display: flex;

    .r-h-title {
      height: 30px;
      line-height: 30px;
      font-size: 20px;
      font-weight: 600;
      color: #555;
      display: flex;
      text-align: center;

      .iconfont {
        margin: auto 0;
        font-weight: 700;
        font-size: 28px;
        height: 30px;
      }
    }
  }

  .r-search {
    display: flex;
    height: 30px;
    line-height: 30px;
    margin: 20px 0 0 0;
    padding-bottom: 10px;
    border-bottom: 2px solid @lineColor;

    .r-s-input {
      height: 30px;
      line-height: 30px;
      width: 20%;
    }

    .r-s-btn {
      margin: auto 20px;
    }
  }

  .r-table {
    user-select: none;

    .table {
      height: 72vh;

      .btns {
        display: flex;

        .btn {
          margin: auto 5px;
        }
      }

    }



    .btns {
      display: flex;
      justify-content: center;

      .btn {
        margin: auto 5px;
      }
    }
  }

  .r-footer {
    margin: auto auto 0 auto;
    display: flex;
    justify-content: center;
  }
}

.teaminput {
  display: flex;
  flex-direction: column;

  .box {
    display: flex;
    height: 30px;
    line-height: 30px;

    .input {
      width: 80%;
      margin: 2px auto;
    }

    .btn {
      margin: auto;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: right;

  .btn {
    margin: auto 5px;
  }
}


.btn {
  margin: auto 5px;
}

.h1box {
  display: flex;
  margin-top: 5px;

  .popselect {
    width: 15%;
    margin: auto 10px auto 0;
  }

  .r-s-input {
    width: 20%;
    margin: auto 10px auto 0;
  }
}


.drawer {
  .table {
    height: 80vh;
  }

  .footer {
    display: flex;
    justify-content: center;
    margin-top: 5px;
  }
}
</style>